
package com.chuangan.releasetask.controller;

import com.chuangan.releasetask.Utils.*;
import com.chuangan.releasetask.VO.ResultVO;
import com.chuangan.releasetask.dto.WebDTO;
import com.chuangan.releasetask.enums.ResultEnum;
import com.chuangan.releasetask.exception.ReleaseTaskException;
import com.chuangan.releasetask.mapper.SysConfigMapper;
import com.chuangan.releasetask.mapper.TaskMapper;
import com.chuangan.releasetask.mapper.UserMapper;
import com.chuangan.releasetask.pojo.*;
import com.chuangan.releasetask.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jinLong
 * @Date: 2020/8/12 15:27
 * @Version 1.0
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;


    /**
     * 功能描述: 用户注册
     *
     * @Return: com.chuangan.releasetask.VO.ResultVO
     * @Author: jinLong
     * @Date: 2020/8/12 15:34
     */
    @RequestMapping("/register")
    public ResultVO register(@RequestBody WebDTO webDTO) {
        if (StringUtils.isEmpty(webDTO.getUserAccount()) || StringUtils.isEmpty(webDTO.getCode())) {
            return ResultVOUtil.error(202, "手机号码或验证码参数异常");
        }
        //查询是否已经存在相同的手机号
        if (!StringUtils.isEmpty(webDTO.getUserAccount())) {
            //根据手机号去查询用户是否已经注册
            User user = userService.findOneUser(webDTO.getUserAccount());
            if (user != null) {
                return ResultVOUtil.error(203, "此手机号码已经注册!");
            }
        }

        if (!StringUtils.isEmpty(webDTO.getShareCode())) {
            //判断邀请码是否为空
            User user = userMapper.findOneUserByID(ShareCodeUtils.codeToId(webDTO.getShareCode()).intValue());
            webDTO.setUserInvitor(user.getUserAccount());
            webDTO.setUserEstate(user.getUserEstate() + 1);
        }


        //密码加密
        webDTO.setUserPassword(PasswordUtil.generate(webDTO.getUserPassword()));
        webDTO.setUserInvitor("无");
        webDTO.setUserEstate(1);

        try {
            //用户注册
            userService.register(webDTO);
            userMapper.addNewcomerAward(webDTO.getUserAccount());
            userMapper.addInvitedNum(webDTO.getUserAccount());
            userMapper.addInvitedNum(webDTO.getUserInvitor());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统繁忙，注册失败!");
        }
        return ResultVOUtil.success("注册成功!");
    }

    /**
     * 功能描述: 发送短信验证码
     *
     * @Return: void
     * @Author: jinLong
     * @Date: 2020/8/14 16:47
     */
    @PostMapping("/sendSsm")
    public ResultVO sendSsm(@RequestParam("userAccount") String userAccount) {
        String code = "";
        Map map = new HashMap();
        try {
            if (StringUtils.isEmpty(userAccount)) {
                return ResultVOUtil.error(204, "手机号码不能空！");
            }
            // redis缓存验证码
            try {
                Random random = new Random();
                for (int i = 0; i < 6; i++) {
                    code += random.nextInt(10);
                }
                redisTemplate.opsForValue().set(userAccount + "code", code, 1800, TimeUnit.SECONDS);
                SmsUtils.sendSsm(userAccount, code);
            } catch (Exception e) {
                return ResultVOUtil.error(500, "发送异常,重新发送!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("验证码:", code);
        return ResultVOUtil.success(map);
    }


    /**
     * 功能描述: APP登录
     *
     * @Return: void
     * @Author: jinLong
     * @Date: 2020/8/17 17:34
     */
    @PostMapping("/login")
    public ResultVO login(@RequestBody User user) {
        Map<String, Object> tokenMap = new HashMap<>();
        String token = null;
        try {
            User loginUser = userService.login(user);
            if (loginUser == null) {
                return ResultVOUtil.error(405, "登录或密码错误!");
            }
            //创建Token字符串
            token = jwtUtil.createJWT(String.valueOf(loginUser.getUserAccount()), loginUser.getUserName(), loginUser);
            //校验token是否为空
            if (StringUtils.isEmpty(token)) {
                return ResultVOUtil.error(408, "令牌为空!");
            }
            tokenMap.put("token", token);
            tokenMap.put("loginUser", loginUser);
            //将用户信息存入redis
            redisTemplate.opsForValue().set(loginUser.getUserAccount() + "token", token, 1800, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(loginUser.getUserAccount() + "loginUser", loginUser.toString(), 1800, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultVOUtil.success(tokenMap);
    }


    @RequestMapping("/share")
    public ResultVO share(int userID) {
        String shareCode = ShareCodeUtils.idToCode((long) userID);
        User user = userMapper.findOneUserByID(ShareCodeUtils.codeToId(shareCode).intValue());
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("shareCode", shareCode);
        return ResultVOUtil.success(map);
    }

    @PostMapping(value = "/userVerified", headers = "content-type=multipart/form-data")
    public ResultVO userVerified(String userAccount, String userIDNum, String userRealName, MultipartRequest multipartRequest, HttpServletRequest req) {
        if (StringUtils.isEmpty(userAccount) || StringUtils.isEmpty(userIDNum) || StringUtils.isEmpty(userRealName)) {
            return ResultVOUtil.error(404, "用户ID或用户账号为空");
        }
        User user = userMapper.findOneUser(userAccount);
        user.setUserIDNum(userIDNum);
        user.setUserRealName(userRealName);
        user.setUserFrontImg(FileUtils.uploadImg(multipartRequest.getFile("frontImg"), "frontImg", "userVerified" + "/" + userIDNum + "/", req));
        user.setUserReverseImg(FileUtils.uploadImg(multipartRequest.getFile("reverseImg"), "reverseImg", "userVerified" + "/" + userIDNum + "/", req));
        user.setUserHeldImg(FileUtils.uploadImg(multipartRequest.getFile("heldImg"), "heldImg", "userVerified" + "/" + userIDNum + "/", req));
        userMapper.updateUserVerifiedInfo(user);
        return ResultVOUtil.success(user);
    }


    /**
     * 功能描述: 更新头像
     *
     * @Return: com.chuangan.releasetask.VO.ResultVO
     * @Author: jinLong
     * @Date: 2020/10/12 14:50
     */
    @PostMapping(value = "/updateFace", headers = "content-type=multipart/form-data")
    public ResultVO updateFace(@Valid String userAccount, MultipartRequest multipartRequest, HttpServletRequest req) {
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserFaceUrl(FileUtils.uploadImg(multipartRequest.getFile("userFaceUrl"), "userFaceUrl", "userFaceUrl" + "/" + userAccount + "/", req));
        userMapper.updateFace(user);
        User returnUser = userMapper.findOneUser(userAccount);
        return ResultVOUtil.success(returnUser);
    }

    @RequestMapping("/drawBonus")
    public ResultVO drawBonus(@Valid BonusRecord bonusRecord, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, bonusRecord={}", bonusRecord);
            throw new ReleaseTaskException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.findOneUser(bonusRecord.getUserAccount());
        userMapper.creditCal(user.getUserBalance().add(bonusRecord.getBonus()), bonusRecord.getUserAccount());
        userMapper.addBonusDrawRecord(bonusRecord);
        return ResultVOUtil.success(map);
    }


    @RequestMapping("/userRankingBonus")
    public ResultVO userRankingBonus(String userAccount, String remark) {
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.findOneUser(userAccount);
//        查询新人奖励
        List<SysConfig> sysConfigs = sysConfigMapper.getSysConfigByMemo(remark);
        List<BonusRecord> bonusRecords = new ArrayList<>();
        for (SysConfig sysConfig : sysConfigs) {
            if (sysConfig.getRemark().contains("奖励")) {
                BonusRecord bonusRecord = sysConfigMapper.getBonusDrawRecordByRanking(sysConfig.getParamKey(), userAccount);
                bonusRecords.add(bonusRecord);
            }
        }
        //查询用户的所有完成任务
        List<Map> taskList = userMapper.sumTaskList(userAccount);
        if (StringUtils.isEmpty(taskList)) {
            return ResultVOUtil.error(404, "系统异常，请重新启动");
        }
        map.put("sumTask", taskList.size());
        map.put("user", user);
        map.put("sysConfigs", sysConfigs);
        map.put("bonusRecord", bonusRecords);
        return ResultVOUtil.success(map);
    }


    @RequestMapping("/userFeedBack")
    public ResultVO userFeedBack(String userAccount, String feedBack) {

        FeedBack fb = new FeedBack();
        fb.setUserAccount(userAccount);
        fb.setFeedBack(feedBack);
        userMapper.userFeedBack(fb);

        return ResultVOUtil.success("反馈成功");
    }


    @GetMapping("/myPromotionList")
    public ResultVO myPromotionList(String userAccount) {
        Map<String, Object> map = new HashMap<>();
        BigDecimal totalEarning = new BigDecimal(0);
        BigDecimal todayEarning = new BigDecimal(0);
        int todayPromo = 0;
        Date date = new Date();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        List<BonusRecord> bonusRecords_lv1 = userMapper.selectSumBonusRecordListByAccount("一级任务奖励金", userAccount);
        List<BonusRecord> bonusRecords_lv2 = userMapper.selectSumBonusRecordListByAccount("二级任务奖励金", userAccount);
        if (bonusRecords_lv1.size() != 0) {
            for (BonusRecord bonusRecord : bonusRecords_lv1) {
                totalEarning = totalEarning.add(bonusRecord.getBonus());
            }
        }
        if (bonusRecords_lv2.size() != 0) {
            for (BonusRecord bonusRecord : bonusRecords_lv2) {
                totalEarning = totalEarning.add(bonusRecord.getBonus());
            }
        }
        map.put("totalEarning", totalEarning);
        map.put("totalInvited", bonusRecords_lv1.size());
        map.put("bonusRecords_lv1", bonusRecords_lv1);
        map.put("bonusRecords_lv2", bonusRecords_lv2);
        bonusRecords_lv1.addAll(bonusRecords_lv2);
        for (BonusRecord bonusRecord : bonusRecords_lv1) {
            if (fmt.format(bonusRecord.getCreateTime()).equals(fmt.format(date))) {
                todayEarning = todayEarning.add(bonusRecord.getBonus());
            }
            if (fmt.format(bonusRecord.getFromAccountCreateTime()).equals(fmt.format(date))) {
                todayPromo = todayPromo + 1;
            }
        }
        map.put("todayEarning", todayEarning);
        map.put("todayPromo", todayPromo);
        return ResultVOUtil.success(map);
    }


    /**
     * 功能描述: 新人奖励
     *
     * @Return:
     * @Author: jinLong
     * @Date: 2020/10/15 16:58
     */
    @GetMapping("/newcomerAward")
    public ResultVO newcomerAward(String userAccount) {
        if (StringUtils.isEmpty(userAccount)) {
            return ResultVOUtil.error(404, "缺少参数:用户账号");
        }
        Map maps = new HashMap();
        NewcomerAward award = userMapper.newcomerAward(userAccount);
        List<Map> taskList = userMapper.sumTaskList(userAccount);
        if (StringUtils.isEmpty(award) || StringUtils.isEmpty(taskList)) {
            return ResultVOUtil.error(404, "系统异常，请重新启动");
        }
        maps.put("award", award);
        maps.put("sumTask", taskList.size());
        return ResultVOUtil.success(maps);
    }


    /**
     * 功能描述: 我的任务通用接口
     *
     * @Return:
     * @Author: jinLong
     * @Date: 2020/11/3 14:12
     */
    @RequestMapping("/myTask")
    public ResultVO myTask(@RequestBody WebDTO webDTO) {
        List<Map> userTaskList = userService.selectUserTask(webDTO);
        return ResultVOUtil.success(userTaskList);
    }


    /**
     * 功能描述: 用户版本更新
     *
     * @Return: com.chuangan.releasetask.VO.ResultVO
     * @Author: jinLong
     * @Date: 2020/11/16 18:25
     */
    @RequestMapping("/versions")
    public ResultVO versions(@RequestBody WebDTO webDTO) {
        if (StringUtils.isEmpty(webDTO.getVersions())) {
            return ResultVOUtil.error(500, "获取用户版本错误!");
        }
        if (webDTO.getVersions().compareTo("1.0.2") > 0) {
            return ResultVOUtil.error(200, "true");
        }
        if (webDTO.getVersions().compareTo("1.0.2") == 0) {
            return ResultVOUtil.error(200, "true");
        }
        return ResultVOUtil.error(200, "false");
    }


}








